package org.wzy.design.patterns.proxy.custom;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * ClassName: GPClassLoader <br/>
 * Function: TODO ADD FUNCTION. <br/>
 * Reason: 代码生成、编译、重新动态load到JVM里. <br/>
 * date: 2017年6月15日 上午12:01:09 <br/>
 * 
 * @author wzy_h
 * @version
 * @since JDK 1.8
 */
public class GPClassLoader extends ClassLoader {

	private File baseDir;

	public GPClassLoader() {
		String path = GPClassLoader.class.getResource("").getPath();
		this.baseDir = new File(path);
	}

	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {
		String className = GPClassLoader.class.getPackage().getName() + "." + name;
		if (baseDir != null) {
			File clazzFile = new File(baseDir, name.replaceAll("\\.", "/") + ".class");
			if (clazzFile.exists()) {
				FileInputStream inputStream = null;
				ByteArrayOutputStream out = null;
				try {
					inputStream = new FileInputStream(clazzFile);
					out = new ByteArrayOutputStream();
					byte[] buff = new byte[1024];
					int len;
					while ((len = inputStream.read(buff)) != -1) {
						out.write(buff, 0, len);
					}

					return defineClass(className, out.toByteArray(), 0, out.size());
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					if (null != inputStream) {
						try {
							inputStream.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					if (null != out) {
						try {
							out.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					clazzFile.delete();
				}
			}
		}
		return super.findClass(name);
	}
}
